package com.xjl.remotelink;

import com.xjl.remotelink.client.ClientCallback;
import com.xjl.remotelink.client.ClientThread;
import com.xjl.remotelink.server.ServerCallback;
import com.xjl.remotelink.server.ServerThread;
import com.xujl.task.RxExecutor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RemoteLinkManager {
    private Map<Integer, List<ServerThread>> mServerThreadMap = new HashMap<>();
    private Map<Integer, List<ClientThread>> mClientThreadMap = new HashMap<>();

    private RemoteLinkManager () {
        RxExecutor.getInstance().init();
    }

    public synchronized void createServer (int linkPort, ServerCallback callback) {
        final ServerThread serverThread = new ServerThread(linkPort, callback);
        List<ServerThread> serverThreads = mServerThreadMap.get(linkPort);
        if (serverThreads == null) {
            serverThreads = new ArrayList<>();
            mServerThreadMap.put(linkPort, serverThreads);

        }
        serverThreads.add(serverThread);
        RxExecutor.getInstance().executeRunnableTask(serverThread);
    }

    public void createClient (String data, int linkPort, ClientCallback callback) {
        final ClientThread clientThread = new ClientThread(linkPort, data, callback);
        List<ClientThread> clientThreads = mClientThreadMap.get(linkPort);
        if (clientThreads == null) {
            clientThreads = new ArrayList<>();
            mClientThreadMap.put(linkPort, clientThreads);
        }
        clientThreads.add(clientThread);
        RxExecutor.getInstance().executeRunnableTask(clientThread);
    }

    public void stopThreads (int linkPort) {
        final List<ServerThread> serverThreads = mServerThreadMap.remove(linkPort);
        final List<ClientThread> clientThreads = mClientThreadMap.remove(linkPort);
        if (serverThreads != null) {
            for (ServerThread thread : serverThreads) {
                stopThread(thread);
            }
        }
        if (clientThreads != null) {
            for (ClientThread thread : clientThreads) {
                stopThread(thread);
            }
        }
    }

    private void stopThread (BaseThread thread) {
        if (thread != null) {
            thread.setExit(true);
        }
    }

    public static RemoteLinkManager getInstance () {
        return Holder.MANAGER;
    }


    private static final class Holder {
        private static final RemoteLinkManager MANAGER = new RemoteLinkManager();
    }
}
